import { defineStore } from 'pinia'
import { loginAPI, refreshTokenAPI } from '@/api/auth'
import type { AuthSuccessType, LoginType } from '@/types/auth'
import type { UserStateType } from '@/stores/modules/types/userState'
import { store } from '@/stores'
import { formatFileUrl } from '@/utils/fileUtils'
import WebSocketEvent from '@/event/webSocketEvent'
import router from '@/router'
import type { SysUserDetailsType, SysUserEditType } from '@/views/admin/system/user/utils/model'

export const useUserStore = defineStore({
  id: 'simple-user',
  state: (): UserStateType => ({
    user: {} as SysUserDetailsType,
    accessToken: null,
    refreshToken: null,
    expires: null,
    permissions: []
  }),
  getters: {
    getUser(): SysUserDetailsType {
      return this.user
    },
    getToken(): string | null {
      return this.accessToken
    },
    /**
     * 获取用户角色名
     */
    getRole(): string[] {
      return this.user.roles.map((item) => item.code)
    }
  },
  actions: {
    getUserAvatar(): string {
      if (!this.user.avatar?.includes('http')) {
        return formatFileUrl(this.user.avatar)
      }
      return this.user.avatar as string
    },
    /**
     * 更新用户信息
     * @param user 用户信息
     */
    updateUser(user: SysUserEditType) {
      this.user.name = user.name
      this.user.phone = user.phone as string
      this.user.sex = user.sex
      this.user.birthday = user.birthday
    },
    /**
     * 更新用户头像
     * @param avatar 头像地址
     */
    updateUserAvatar(avatar: string) {
      this.user.avatar = avatar
    },
    /**
     * 账号密码登录
     * @param data 请求参数
     */
    loginByPassword(data: LoginType): Promise<AuthSuccessType> {
      return new Promise<AuthSuccessType>((resolve, reject) => {
        loginAPI(data)
          .then((res) => {
            resolve(res.data)
            this.loginSuccess(res.data)
          })
          .catch((err) => {
            reject(err)
          })
      })
    },
    /**
     * 刷新token
     */
    handRefreshToken(): Promise<AuthSuccessType> {
      if (this.refreshToken == null) {
        return Promise.reject('refreshToken is null')
      }
      return new Promise<AuthSuccessType>((resolve, reject) => {
        refreshTokenAPI(this.refreshToken)
          .then((res) => {
            resolve(res.data)
            this.loginSuccess(res.data)
          })
          .catch((err) => {
            this.logout()
            reject(err)
          })
      })
    },
    /**
     * 登录成功
     * @param data 登录成功返回的数据
     */
    loginSuccess(data: AuthSuccessType) {
      this.user = data.user
      this.accessToken = data.accessToken
      this.refreshToken = data.refreshToken
      this.expires = data.expires
      this.permissions = data.permissions
    },
    /**
     * 退出登录
     */
    logout() {
      this.user = {} as SysUserDetailsType
      this.accessToken = null
      this.refreshToken = null
      this.expires = null
      this.permissions = []
      router.push('/login')
    }
  },
  persist: {
    key: 'simple-user',
    storage: localStorage
  }
})

export function useUserStoreHook() {
  return useUserStore(store)
}

// 监听token失效
WebSocketEvent.on('on:tokenInvalid', async () => {
  // 刷新token
  await useUserStoreHook().handRefreshToken()
})
